package com.itheima.aspect;

import com.itheima.mapper.EmpLoginLogMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.EmpLoginLog;
import com.itheima.pojo.LoginInfo;
import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j
@Component
@Aspect
public class LoginLogAspect {

    @Autowired
    private EmpLoginLogMapper empLoginLogMapper;

    @Around("execution(* com.itheima.controller.LoginController.login(..))")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        log.info("员工执行登录操作, 记录登录日志....");

        EmpLoginLog loginLog = new EmpLoginLog();

        //获取方法参数
        Object[] args = proceedingJoinPoint.getArgs();
        Emp emp = (Emp) args[0];

        loginLog.setUsername(emp.getUsername());
        loginLog.setPassword(emp.getPassword());
        loginLog.setLoginTime(LocalDateTime.now());

        long start = System.currentTimeMillis(); //原始方法运行开始时间

        //调用原始方法
        Object obj = proceedingJoinPoint.proceed();

        long end = System.currentTimeMillis(); //原始方法运行开始时间

        //获取登录结果,是否成功
        Result result = (Result) obj;
        Integer code = result.getCode();
        loginLog.setIsSuccess(code.shortValue());

        if(code == 1){
            Object data = result.getData();
            LoginInfo info = (LoginInfo) data;
            loginLog.setJwt(info.getToken());
        }
        loginLog.setCostTime(end - start);

        //保存登录日志
        empLoginLogMapper.insert(loginLog);
        return obj;
    }

}